<?php

define('FILENAME', 'synonyms');
define('SEPARATOR', '.');
define('EXTENSION', '.txt');

define('UNKNOWN',  'UNKNOWN');
define('MASCULINE', 'MASCULINE');
define('FEMININE',  'FEMININE');

/**
 * Converts an associative array of arbitrary depth and dimension into JSON representation.
 *
 * NOTE: If you pass in a mixed associative and vector array, it will prefix each numerical
 * key with "key_". For example array("foo", "bar" => "baz") will be translated into
 * {'key_0': 'foo', 'bar': 'baz'} but array("foo", "bar") would be translated into [ 'foo', 'bar' ].
 *
 * @param $array The array to convert.
 * @return mixed The resulting JSON string, or false if the argument was not an array.
 * @author Andy Rusterholz
 */
function array_to_json( $array ){

    if( !is_array( $array ) ){
        return false;
    }
	
    $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if( $associative ){

        $construct = array();
        foreach( $array as $key => $value ){

            // We first copy each key/value pair into a staging array,
            // formatting each key and value properly as we go.

            // Format the key:
            if( is_numeric($key) ){
                $key = "key_$key";
            }
            $key = "'".addslashes($key)."'";

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "'".addslashes($value)."'";
            }

            // Add to staging array:
            $construct[] = "$key: $value";
        }

        // Then we collapse the staging array into the JSON form:
        $result = "{ " . implode( ", ", $construct ) . " }";

    } else { // If the array is a vector (not associative):

        $construct = array();
        foreach( $array as $value ){

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "'".addslashes($value)."'";
            }

            // Add to staging array:
            $construct[] = $value;
        }

        // Then we collapse the staging array into the JSON form:
        $result = "[ " . implode( ", ", $construct ) . " ]";
    }

    return $result;
}

function changerToutEncode($string) {
	$addr = strtr($addr, "äåö", "aao");
	return $coded_string;
}

function changerToutDecodeToText($codedString) {
	
	$stringText = strtr($codedString, "_", " ");
	$stringText = trim($stringText);
	return $stringText;
}

function changerToutDecodeToDisplay($codedString) {
/*
	Input:
	Maître_Corbeau, sur un_arbre perché, tenait en_son_bec un_fromage.
	
	Result:
	<span>Maître Corbeau</span>, <span>sur</span> <span>un arbre</span> <span>perché</span>, <span>tenait</span> <span>en son bec</span> <span>un fromage</span>.
*/

	$stringDisplay = preg_replace(
		array('/^(.*)$/',
		'/ /',
		'/([\',\.])/',
		'/([a-zA-Z]+) /',
		'/_/',
		), 
		array('<span>\1',
		' <span>',
		'</span>\1',
		'\1</span> ',
		' '		
		), 
		$codedString);
	
	return $stringDisplay;
}

function curl_get_contents($request_url) {

    $proxy_name = 'proxy.scr.siemens.com';
    $proxy_port = 80;
    $proxy_cont = '';
	$host = parse_url($request_url, PHP_URL_HOST);
	
	
	//Initialize the Curl session
	$ch = curl_init();
	
	//Set curl to return the data instead of printing it to the browser.
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	//Set the URL
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_URL, $request_url);	
	  
	//Execute the fetch
	if (! $data = curl_exec($ch) ) {
		var_dump(curl_error($ch));
	}
	//Close the connection
	curl_close($ch);
	
	return $data;
}
	
global $normalizeChars;
$normalizeChars = array(
    'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A',
    'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I',
    'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U',
    'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a',
    'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i',
    'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u',
    'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f'
);
	
global $masc_endings;
$masc_endings = array(
	4 => array('taire', 'iste'),
	3 => array('age', 'eme', 'ert', 'lon', 'non', 'ome', 'ron', 'sme', 'ton', 'tre'),
	2 => array('an', 'in', 'is ', 'us'),
	1 => array('c', 'd', 'g', 'i', 'k', 'l', 'm', 'o', 'r', 't', 'u')
);

global $fem_endings;
$fem_endings = array(
	5 => array('aison', 'image'),
	4 => array('iere', 'eure'),
	3 => array('ade', 'eur', 'ine', 'ion', 'ite', 'lle', 'tte', 'ote', 'ude', 'ure'),
	2 => array('ce', 'ee', 'ie', 'se')
);

function isFeminine($w) {
	return (getMasculinePoints($w)<getFemininePoints($w));
}
function isMasculine($w) {
	return (getMasculinePoints($w)>getFemininePoints($w));
}

function getFemininePoints($w) {
	global $fem_endings;
	global $normalizeChars;
	for($i = 5; $i>1; $i--) {	
		$w = strtr($w, $normalizeChars);	
		if (in_array(substr($w, -$i), $fem_endings[$i])) {
			return $i;
		}
	}
	return 0;
}

function getMasculinePoints($w) {
	global $masc_endings;
	global $normalizeChars;
	for($i = 4; $i>0; $i--) {
		$w = strtr($w, $normalizeChars);
		if (in_array(substr($w, -$i), $masc_endings[$i])) {		
			return $i;
		}
	}
	return 0;
}

function getGenreDetails($w) {
	return ($w.' (M'.getMasculinePoints($w).'/F'.getFemininePoints($w).')');
}

function genre($w) {
	if (isFeminine($w)) return FEMININE;
	if (isMasculine($w)) return MASCULINE;
	return UNKNOWN;
}

$determinants = array("d’un", "d’une", "d'un","d'une",'un','une','le','la',"l'",'mon','ton','son','ma','ta','sa','cet','cette');


function getSynonymListCNRS($word, $lang, $debug=false) {

switch($lang) {
	case 'FR':
			$urlword = utf8_decode(urldecode($word));
			/* 
			// Pour synonymes.com, on repasse en iso
			$pageContent = curl_get_contents('http://www.synonymes.com/synonyme.php?mot='.$urlword.'&x=0&y=0', false, $context);
			$pageContent = mb_convert_encoding( $pageContent, 'UTF-8');
			$regex = "/synonyme\.php\?mot\=([a-zA-Z ]*)\'/";
			preg_match_all($regex, $pageContent, $results);
			$_SESSION['dictionnary'][$lang][$word] = $results[1];
			if ($ucfirst) {
				foreach( $results[1] as &$w ) { $w = ucdictionnary($w); }
				echo json_encode($results[1]);
			} else {
				echo json_encode($results[1]);
			}
			*/
			$url = 'http://dico.isc.cnrs.fr/dico/fr/chercher?r='.$urlword;
			$pageContent = file_get_contents($url);
			// Le contenu de cnrs est en ISO-8859-1 passage a utf
			$pageContent = iconv('ISO-8859-1', 'UTF-8', $pageContent);

			$regex = '#\<A HREF=chercher\?r\=([^\>]*)\>([^\<]*)\<\/A\>#s';
			preg_match_all($regex, $pageContent, $results);
			return $results[2];
		break;
		
	case 'EN':
	
			$pageContent = file_get_contents('http://dico.isc.cnrs.fr/dico/en/search?b=1&r='.$word.'&send=Look+it+up', false);
			if ($debug) 
			echo '"debugUrl": "http://dico.isc.cnrs.fr/dico/en/search?b=1&r='.$word.'&send=Look+it+up", ';
			$regex = "/1&r\=([a-zA-Z%0-9 ]*)/";
			preg_match_all($regex, $pageContent, $results);
			foreach($results[1] as &$value)
				$value = urldecode($value);			
			
			return $results[1];
		break;
}

}



function getSynonymListSensagent($word, $lang, $type='ALL', $debug=false) {
	
	if ($lang == 'EN')
		$url = 'http://dictionary.sensagent.com/'.$word.'/en-en/';
	else
		$url = 'http://dictionary.sensagent.com/'.$word.'/fr-fr/';

	if ($debug) {
		echo 'url: <a href="', $url,'">', $url ,'</a>'; 
	}

	$pageContent = file_get_contents($url);
	$pageContent = substr($pageContent, strpos($pageContent, 'divSynonyms'));
	$pageContent = substr($pageContent, 0, strpos($pageContent, 'class="title"'));


	$regex = '#<span class="posp">\([^\)]*\)</span></h2><p class="synonyms">(?:<a (?:[^>]*)><span class="wording">[^<]*</span></a>,? ?)+#s';
	//$regex = '#<span class="posp">\([a-zA-Z]*\.\)</span></h2><p class="synonyms">#s';
	preg_match_all($regex, $pageContent, $results);


	$synonyms = array();
	foreach($results[0] as $listing) {

		$regex = '#<span class="posp">\(([a-z\.]*)\)</span>#';
		preg_match($regex, $listing, $key);
		
		$regex = '#<span class="wording">([^<]*)</span>#';
		preg_match_all($regex, $listing, $words);
		
		switch($type) {
		case 'v':
		case 'v.':
		case 'verb':
			if ($key[1] == 'v.')
				$synonyms = array_merge($synonyms, $words[1]);
			break;
		case 'n':
		case 'n.':
		case 'nom':
		case 'nominal':
		case 'noun':
			if ($key[1] == 'n.' || $key[1] == 'n.')
				$synonyms = array_merge($synonyms, $words[1]);
			break;
		default:
			$synonyms = array_merge($synonyms, $words[1]);
		break;
		}
	}
	
	return $synonyms;
}